<?php
/**
 * 小蜗牛留言本
 * 本文件内代码属于“小蜗牛留言本”项目，禁止修改再发布本程序源码，禁止去除页面底部的版权申明。所有版权保留
 * User: upliu
 * Email: 753073861@qq.com
 * QQ: 753073861
 * 程序主页：http://demo.upliu.net/snail-guestbook/
 */

define('ADMIN_USER_STATUS_ACTIVE', 10);
define('ADMIN_USER_STATUS_FORBIDDEN', 20);

define('RETURN_STATUS_SUCCESS', 0);
define('RETURN_STATUS_FAIL', 1);

function is_installed()
{
    return file_exists(__DIR__ . '/../config.php');
}

function get_admin_user_status_desc($status)
{
    $map = array(
        ADMIN_USER_STATUS_ACTIVE => '启用',
        ADMIN_USER_STATUS_FORBIDDEN => '禁用',
    );

    return $map[$status];
}

function logout()
{
    unset($_SESSION['user']);
    redirect_path('admin/login.php');
}

function check_login()
{
    if (!is_login()) {
        redirect_path('admin/login.php');
    }
}

function is_login()
{
    return !empty($_SESSION['user']);
}

function get_current_login_user_info($key = null)
{
    $user = $_SESSION['user'];
    if ($key) {
        return $user[$key];
    }

    return $user;
}

/**
 * 当前登录用户是否可以处理（回复，删除）指定部门的留言
 * 超级管理员都可以进行管理
 * @param $dept_id int 0=未指定部门，所有管理员用户都可以进行处理
 * @return bool
 */
function is_current_login_user_can_handle($dept_id)
{
    if ($dept_id == 0) {
        return true;
    }

    if (is_current_login_user_super_admin()) {
        return true;
    }

    return $_SESSION['user']['dept_id'] = $dept_id;
}

function is_current_login_user_super_admin()
{
    return get_current_login_user_info('dept_id') == 0;
}

function admin_user_login($username, $input_password)
{
    $user = find_user_by_username($username);
    if (!$user) {
        return array('status' => RETURN_STATUS_FAIL, 'message' => '用户不存在');
    }

    if (!is_password_pass($user['salt'], $user['password'], $input_password)) {
        return array('status' => RETURN_STATUS_FAIL, 'message' => '密码错误');
    }

    if ($user['status'] == ADMIN_USER_STATUS_FORBIDDEN) {
        return array('status' => RETURN_STATUS_FAIL, 'message' => '您的账户被禁用');
    }

    $_SESSION['user'] = $user;

    return array('status' => RETURN_STATUS_SUCCESS);
}

function delete_admin_user_by_id($user_id)
{
    $user_id = (int)$user_id;
    return Db::getInstance()->execute("delete from admin_user where id=$user_id");
}

function get_user_list()
{
    return Db::getInstance()->queryAll("select * from admin_user");
}

function set_admin_user_active($user_id)
{
    return set_admin_user_status($user_id, ADMIN_USER_STATUS_ACTIVE);
}

function set_admin_user_forbidden($user_id)
{
    return set_admin_user_status($user_id, ADMIN_USER_STATUS_FORBIDDEN);
}

function set_admin_user_status($user_id, $status)
{
    $user_id = (int)$user_id;
    return Db::getInstance()->execute("update admin_user set status=$status where id=$user_id");
}

function change_admin_user_info($user_id, $data)
{
    $user_id = (int)$user_id;
    if (!empty($data['password'])) {
        $salt = generate_salt();
        $password = generate_password($salt, $data['password']);
        $data['salt'] = $salt;
        $data['password'] = $password;
    } else {
        unset($data['password']);
        unset($data['salt']);
    }
    $data['dept_id'] = (int)$data['dept_id'];

    // 只能更改密码和部门信息
    foreach ($data as $k => $v) {
        if (!in_array($k, array('salt','password','dept_id'))) {
            unset($data[$k]);
        }
    }

    return Db::getInstance()->update('admin_user', $data, "id=$user_id");
}

function change_admin_user_password($user_id, $new_password)
{
    $salt = generate_salt();
    $password = generate_password($salt, $new_password);

    Db::getInstance()->execute("update admin_user set salt=?,password=? where id=?", array($salt, $password, $user_id));
}

function add_admin_user($username, $password, $dept_id, $status = 10)
{
    $salt = generate_salt();
    $password_md5 = generate_password($salt, $password);
    $user_id = Db::getInstance()->insert('admin_user', array(
        'salt' => $salt,
        'username' => $username,
        'password' => $password_md5,
        'dept_id' => $dept_id,
        'status' => $status,
    ));

    return $user_id;
}

function is_password_pass($salt, $password_in_db, $user_input_password)
{
    return generate_password($salt, $user_input_password) == $password_in_db;
}

function generate_salt()
{
    return substr(uniqid(), -6);
}

function generate_password($salt, $password)
{
    return md5($salt . $password);
}

function add_note_reply($note_id, $content, $user_id)
{
    $create_time = date('Y-m-d H:i:s');
    $dept_id = get_user_info($user_id, 'dept_id');
    $db = Db::getInstance();
    $apply_id = $db->insert('note_reply', array(
        'create_time' => $create_time,
        'content' => $content,
        'user_id' => $user_id,
        'dept_id' => $dept_id,
        'reply_note_id' => $note_id,
    ));

    if ($apply_id > 0) {
        $db->execute("update note set is_replied=1 where id=$note_id");
    }

    return $apply_id;
}

function find_user_by_username($username)
{
    return Db::getInstance()->query("select * from admin_user where username=?", array($username));
}

function get_user_info($user_id, $column = null)
{
    $user_id = (int)$user_id;
    if ($column) {
        return Db::getInstance()->queryColumn("select `$column` from admin_user where id=$user_id");
    } else {
        return Db::getInstance()->query("select * from admin_user where id=$user_id");
    }
}

/**
 * 删除指定 ID 的留言，如果删除成功返回值大于 0 ，否则等于 0
 * @param $note_id
 * @return int
 */
function delete_note($note_id)
{
    if (is_current_login_user_super_admin()) {
        return Db::getInstance()->execute("delete from note where id=$note_id");
    }

    $dept_id = get_current_login_user_info('dept_id');

    return Db::getInstance()->execute("delete from note where id=$note_id and (dept_id=0 or dept_id=$dept_id)");
}

function add_note(array $data)
{
    $ip = ip2long(get_client_ip());
    $create_time = date('Y-m-d H:i:s');

    $data += array(
        'ip' => $ip,
        'create_time' => $create_time,
    );

    $db = Db::getInstance();
    $note_id = $db->insert('note', $data);

    return $note_id;
}

function add_dept($name)
{
    return Db::getInstance()->insert('admin_dept', array(
        'name' => $name
    ));
}

function is_success($return)
{
    if (isset($return['status']) && $return['status'] != RETURN_STATUS_SUCCESS) {
        return false;
    }

    return true;
}

function get_dept_name_by_id($dept_id)
{
    static $depts;
    if ($depts === null) {
        $depts = get_depts();
        $depts[0] = '管理员';
    }

    return $depts[$dept_id];
}

function delete_dept_by_id($id)
{
    $id = (int)$id;
    return Db::getInstance()->execute("delete from admin_dept where id=$id");
}

function set_dept_is_show($id, $is_show)
{
    $id = (int)$id;
    $is_show = $is_show ? 1 : 0;
    return Db::getInstance()->execute("update admin_dept set is_show=$is_show where id=$id");
}

function get_dept_list($only_show = false)
{
    $db = Db::getInstance();
    if ($only_show) {
        $depts = $db->queryAll("select * from admin_dept where is_show=1");
    } else {
        $depts = $db->queryAll("select * from admin_dept");
    }

    return $depts;
}

function get_depts($only_show = false)
{
    $depts = get_dept_list($only_show);
    $result = array_column($depts, 'name', 'id');

    return $result;
}

function get_notes_with_reply($where, $page, $page_size = 20)
{
    $notes = get_notes($where, $page, $page_size);
    $note_ids = array_column($notes, 'id');

    $db = Db::getInstance();

    $replys = $db->queryAllWhereIn("select * from note_reply", 'reply_note_id', $note_ids);
    $replys = array_index($replys, 'reply_note_id');

    return array(
        'notes' => $notes,
        'replys' => $replys,
    );
}

function get_note_by_id($note_id)
{
    return Db::getInstance()->query("select * from note where id=$note_id");
}

function get_notes($where, $page, $page_size = 20)
{
    $offset = ($page - 1) * $page_size;
    $db = Db::getInstance();
    return $db->queryAll("select * from note $where order by id desc limit $offset, $page_size");
}

function get_note_count($where = '')
{
    $db = Db::getInstance();
    $count = $db->queryColumn("select count(*) from note $where");
    return (int)$count;
}

function get_notes_pagination($current_page, $page_param, $page_size, $dept_id = null, $only_not_replied = false)
{
    $where = "where 1=1";
    if (is_numeric($dept_id)) {
        $where .= " and dept_id=0 or dept_id=$dept_id";
    } else {
        $where .= "";
    }
    if ($only_not_replied) {
        $where .= " and is_replied=0";
    }
    $total_count = get_note_count($where);
    try {
        check_is_correct_page($current_page, $total_count, $page_size);
    } catch (\Exception $e) {
        // 如果是走到这一步，说明是用户手动输入了一个不存在的页码
        die($e->getMessage());
    }
    $data = get_notes_with_reply($where, $current_page, $page_size);
    $notes = $data['notes'];
    $replys = $data['replys'];

    $pagination = pagination($_SERVER['REQUEST_URI'], $total_count, $page_size, $current_page, $page_param);

    return array(
        'notes' => $notes,
        'replys' => $replys,
        'pagination' => $pagination,
    );
}
